<template>
  <div>
    <el-form ref="formRef" :inline="true" :model="queryParams" class="demo-form-inline">
      <el-form-item label="角色名称">
        <el-input v-model="queryParams.roleName" placeholder="请输入角色名称" clearable />
      </el-form-item>
      <el-form-item label="权限字符">
        <el-input v-model="queryParams.roleKey" placeholder="请输入权限字符" clearable />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.status" placeholder="状态" clearable style="width: 240px">
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="创建时间">
        <el-date-picker v-model="dateRange" @change="handleDateRangeChange" value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" />
      </el-form-item> -->
      <el-row>
        <el-form-item>
          <el-button v-p="['system:role:query']" type="primary" @click="searchEvent">搜索</el-button>
          <el-button v-p="['']" type="default" @click="resetEvent">重置</el-button>
          <el-button v-p="['system:role:add']" type="primary" plain @click="handleAdd()">新增</el-button>
          <el-button
            v-p="['system:role:remove']"
            type="danger"
            plain
            @click="deleteEvent()"
            :disabled="selected.length <= 0"
            :loading="deleteLoading"
          >
            删除
          </el-button>
        </el-form-item>
      </el-row>
    </el-form>
    <el-table
      v-loading="loading"
      :data="tableData"
      @selection-change="handleSelectionChange"
      height="100%"
      class-name="small-padding fixed-width"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="角色编号" align="center" key="roleId" prop="roleId" />
      <el-table-column label="角色名称" align="center" key="roleName" prop="roleName" :show-overflow-tooltip="true" />
      <el-table-column label="权限字符" align="center" key="roleKey" prop="roleKey" :show-overflow-tooltip="true" />
      <el-table-column label="显示顺序" align="center" key="roleSort" prop="roleSort" :show-overflow-tooltip="true" />
      <el-table-column label="状态" align="center" key="status">
        <template v-slot="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template v-slot="scope"> {{ scope.row.createTime.split(" ")[0] }} </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="fixed-width">
        <template v-slot="scope">
          <div style="display: flex; justify-content: space-evenly; align-items: center">
            <el-button type="primary" v-if="!scope.row.admin" v-p="['system:role:edit']" link @click="handleUpdate(scope.row)">
              修改
            </el-button>
            <el-button
              type="primary"
              v-if="!scope.row.admin"
              v-p="['system:role:remove']"
              link
              @click="deleteEvent(scope.row.roleId)"
            >
              删除
            </el-button>
            <el-dropdown v-if="!scope.row.admin">
              <el-button type="primary" link>更多</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>
                    <el-button type="primary" link @click="handleAuthRole(scope.row)">分配用户</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button type="primary" link @click="handlePersmission(scope.row)">分配数据权限</el-button>
                  </el-dropdown-item>
                  <!-- <el-dropdown-item>
                    <el-button type="primary" v-if="!scope.row.admin" link icon="Key"
                      @click="deleteEvent(scope.row)">数据权限</el-button>q
                  </el-dropdown-item> -->
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @update:page="handlePageChange"
      @update:limit="handlePageSizeChange"
    />
    <el-dialog :title="title" v-model="open" width="600px" append-to-body :destroy-on-close="true" @close="cancelHandler">
      <el-form ref="formDataRef" :model="formData" :rules="rules" label-width="80px" class="dept-form" >
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="formData.roleName" placeholder="请输入角色名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限字符" prop="roleKey">
              <el-input v-model="formData.roleKey" placeholder="请输入权限字符" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色顺序" prop="roleSort">
              <el-input-number :min="0" :max="999" v-model="formData.roleSort" placeholder="请输入角色顺序" maxlength="3" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="formData.status">
                <el-radio v-for="item in statusList" :key="item.value" :label="item.value" v-model="item.value">{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 菜单权限 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="菜单权限" class="menu-permission">
              <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
              <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
              <!-- <el-checkbox v-model="formData.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox> -->
              <el-col :span="24">
                <el-tree
                  class="tree-border"
                  empty-text="加载中，请稍候"
                  show-checkbox
                  ref="menuRef"
                  node-key="id"
                  :data="menuOptions"
                  :props="defaultProps"
                  :check-strictly="false"
                  @check-change="handleNodeClick"
                ></el-tree>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 备注 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer" style="text-align: right">
          <el-button type="primary" @click="submitForm(formDataRef)">确 定</el-button>
          <el-button @click="cancel(formDataRef)">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible" title="授权" width="800" :before-close="handleClose">
      <el-transfer
        :data="allUserList"
        v-model="hasUserList"
        :titles="['所有用户', '拥有用户']"
        :button-texts="['取消授权', '添加授权']"
        :props="{ label: 'userName', key: 'userId' }"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savaHasRole" :disabled="isDisabled">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import type { FormInstance, FormRules } from "element-plus";
import {
  roleMenuTreeSelectApi,
  allocatedListApi,
  authUserSelectAllApi,
  roleListApi,
  userListApi,
  delRoleApi,
  roleIdApi,
  updateRoleApi,
  menuListApi,
  getMenuTreeSelectApi,
addRoleApi
} from "@/api";
import { reactive, ref, onMounted } from "vue";
import router from "@/routers";
import { useRoleDataStore } from "@/stores";
import { ElMessage, ElMessageBox } from "element-plus";
import Pagination from "@/components/pagination/Pagination.vue";
import { nextTick } from "vue";
import { ElTree } from "element-plus";

const useRoleData = useRoleDataStore();
// 表单
const formRef = ref<FormInstance>();

// 查询参数
const queryParams = reactive({
  roleName: "",
  roleKey: "",
  status: "",
  pageNum: 1,
  pageSize: 10
});

// 搜索
const searchEvent = () => {
  getRoleList();
};

// 重置

const resetEvent = () => {
  queryParams.roleName = "";
  queryParams.roleKey = "";
  queryParams.status = "";
  getRoleList();
};
// 菜单权限
const menuExpand = ref(false);
const menuNodeAll = ref(false);
const menuOptions = ref<any[]>([]);
// const menuRef = ref();
const menuRef = ref<InstanceType<typeof ElTree> | null>(null);
const defaultProps = ref({
  children: "children",
  label: "label"
});
const formData = ref<any>({
  roleName: "",
  roleKey: "",
  roleSort: 0,
  status: "0",
  remark: "",
  menuCheckStrictly: false,
  deptCheckStrictly: false
});
// 树权限（展开/折叠）
const handleCheckedTreeExpand = (value: any, type: any) => {
  if (type == "menu") {
    const treeList = menuOptions.value;
    for (let i = 0; i < treeList.length; i++) {
      if (!menuRef.value) return;
      menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
    }
  }
};
// 树权限（全选/全不选）
const handleCheckedTreeNodeAll = (value: any, type: any) => {
  if (type == "menu") {
    menuRef.value?.setCheckedNodes(value ? menuOptions.value : []);
  }
};

// 树权限（父子联动）
// const handleCheckedTreeConnect = (value: any, type: any) => {
//   if (type == "menu") {
//     formData.value.menuCheckStrictly = value ? true : false;
//   }
// };
const allData = ref([]); // 存储所有数据

// 节点备点击回调
const handleNodeClick = async () => {
  const checkedKeys = menuRef.value?.getCheckedKeys();
  const allCheckedNodesWithParents: any[] = [];
  if (checkedKeys) {
    checkedKeys.forEach((key) => {
      const node = menuRef.value?.getNode(key);
      if (node) {
        allCheckedNodesWithParents.push(node.data);
        let parent = node.parent;
        while (parent && parent.data) {
          allCheckedNodesWithParents.push(parent.data);
          parent = parent.parent;
        }
      }
    });
    // 去重
    let uniqueCheckedNodesWithParents = Array.from(new Set(allCheckedNodesWithParents.map((node) => JSON.stringify(node)))).map(
      (nodeString) => JSON.parse(nodeString)
    );
    uniqueCheckedNodesWithParents = uniqueCheckedNodesWithParents.filter(
      (item) => typeof item !== "object" || !Array.isArray(item)
    );
    // 去掉最外层的array组成的父节点数组；
    const menuIds = uniqueCheckedNodesWithParents?.map((item) => item.id);
    menuId.value = menuIds;
  } else {
    console.log("树组件未正确初始化");
  }
};

// 获取菜单列表
const getAllData = async () => {
  try {
    const res = await menuListApi();
    if (res.code === 200) {
      allData.value = res.data;
    }
  } catch (error) {
    console.error("Error fetching data", error);
  }
};

// 获取部门列表
const tableData = ref<any[]>([]);
const getRoleList = async () => {
  try {
    const res = await roleListApi({ ...queryParams });
    if (res.code === 200) {
      tableData.value = res.data;
      total.value = res.total as number;
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    console.error("Error fetching data", error);
  }
};

// 多选
const selected = ref<string[]>([]);
const handleSelectionChange = (data: any) => {
  selected.value = data.map((item: any) => {
    return item.roleId;
  });
};

const loading = ref(false);

// 修改
const handleUpdate = async (row: any) => {
  try {
    title.value = "修改部门";
    open.value = true;
    const res = await roleIdApi(row.roleId);
    if (res.code === 200) {
      formData.value = { ...res.data };
    } else {
      ElMessage.error(res.message);
    }
    useRoleData.isEdit = true;
    // 获取菜单列表
    const menuRes = await roleMenuTreeSelectApi(row.roleId);
    if (menuRes.code === 200) {
      menuOptions.value = menuRes.data.menus;
      const checkedKeys = menuRes.data.checkedKeys;
      checkedKeys.forEach((v: any) => {
        nextTick(() => {
          if (menuRef.value) {
            menuRef.value.setChecked(v, true, false);
          }
        });
      });
      menuId.value = menuRes.data.checkedKeys;
    }
  } catch (error) {
    console.error("Error fetching data", error);
  }
};

// 状态
const statusList = ref([
  { value: "0", label: "正常" },
  { value: "1", label: "停用" }
]);

// 删除
const deleteLoading = ref(false);
const deleteEvent = (id?: string) => {
  deleteLoading.value = true;
  if (id) {
    selected.value.push(id);
  }
  try {
    ElMessageBox.confirm("确定删除所勾选的角色吗？删除之后数据将无法恢复", "系统提示", {
      type: "error"
    }).then(async () => {
      // 调用删除接口
      try {
        const res = await delRoleApi(selected.value.join(","));
        if (res.code === 200) {
          ElMessage.success("删除成功");
        } else {
          ElMessage.error(res.message);
        }
      } catch (error) {
        console.error("Error deleting data", error);
      } finally {
        deleteLoading.value = false;
        getRoleList();
        selected.value = [];
      }
    });
  } catch (error) {
    ElMessage.error("删除失败");
  }
};

// 分配用户
const handleAuthRole = async (row: any) => {
  try {
    currentRoleId.value = row.roleId;
    const result = await allocatedListApi(row.roleId);
    if (result.code === 200) {
      hasUserList.value = result.data.map((item: any) => item.userId);
      dialogVisible.value = true;
    }
  } catch (error) {
    console.error("Error fetching data");
  }
};
// 分配权限
const handlePersmission = (row: any) => {
  useRoleData.roleData = { ...row };
  useRoleData.isEdit = true;
  // router.push("system/role-perssionRole");
};

// 弹窗表单
const title = ref("");
const open = ref(false);
const formDataRef = ref<FormInstance>();

const rules = reactive<FormRules>({
  roleName: [{ required: true, message: "角色名称不能为空", trigger: "blur" }],
  roleKey: [{ required: true, message: "权限字符不能为空", trigger: "blur" }],
  roleSort: [{ required: true, message: "角色顺序不能为空", trigger: "blur" }]
});

const menuId = ref<any[]>([]); // 选中的菜单id合集
const cancelHandler = () => {
  formDataRef.value && formDataRef.value.resetFields();
};
// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  // console.log(formEl);
  if (!formEl) return;
  // 编辑调用接口
  if (useRoleData.isEdit) {
    formEl.validate(async (valid: boolean) => {
      if (!valid) return;
      formData.value.menuIds = menuId.value;
      const res = await updateRoleApi(formData.value);
      if (res.code === 200) {
        ElMessage.success("修改成功");
        open.value = false;
        // router.back();
      } else {
        ElMessage.error(res.message);
      }
      // 菜单权限
      // router.push("system/role-perssionRole");
      // useRoleData.roleData = formData.value;
    });
    return;
  }
  // 新增调用接口
  formData.value.menuIds = menuId.value;
  const res = await addRoleApi(formData.value);
  if (res.code === 200) {
    ElMessage.success("添加成功");
    open.value = false;
    // router.back();
  } else {
    ElMessage.error(res.message);
  }
};

// 新增
const handleAdd = async () => {
  title.value = "新增角色";
  open.value = true;
  useRoleData.isEdit = false;
  getMenuTreeSelect();
};
const getMenuTreeSelect = async () => {
  try {
    const res = await getMenuTreeSelectApi();
    if (res.code === 200) {
      menuOptions.value = res.data;
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    console.error("获取菜单失败");
  }
};
// 取消表单
const cancel = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  open.value = false;
  formData.value.remark = "";
  formEl.resetFields();
};

// 分页
const total = ref(0);
const handlePageChange = (page: number) => {
  queryParams.pageNum = page;
  getRoleList();
};

const handlePageSizeChange = (size: number) => {
  queryParams.pageSize = size;
  getRoleList();
};

const dialogVisible = ref<boolean>(false);
const allUserList = ref<any[]>([]);
const hasUserList = ref<any[]>([1, 2, 3]);
const isDisabled = ref<boolean>(false);
const currentRoleId = ref<string>("");
const handleClose = (done: () => void) => {
  done();
};

// 保存用户授权
const savaHasRole = async () => {
  try {
    const data = {
      roleId: currentRoleId.value,
      userIds: hasUserList.value.join(",")
    };
    const result = await authUserSelectAllApi(data);
    if (result.code === 200) {
      ElMessage.success("授权成功");
      getRoleList();
    } else {
      ElMessage.error(result.message);
    }
  } catch (error) {
    ElMessage.error("授权失败，请稍后再试");
  } finally {
    dialogVisible.value = false;
  }
};

// 获取所有用户列表
const getUserList = async () => {
  try {
    const res = await userListApi({ pageNum: 1000 });
    if (res.code === 200) {
      allUserList.value = res.data;
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    ElMessage.error("获取用户数据失败");
  }
};

onMounted(() => {
  getRoleList();
  getUserList();
  getAllData();
});
</script>

<style scoped lang="scss">
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
  border: 1px solid red;
}
.menu-permission {
  .tree-border {
    margin-top: 5px;
    border: 1px solid #e5e6e7;
    background: #ffffff none;
    border-radius: 4px;
  }
}
.dept-form {
  margin-top: 15px !important;
}
</style>
